﻿/*
 * Created by SharpDevelop.
 * User: Kevin
 * Date: 2017/5/13
 * Time: 15:49
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace RestTest
{
	/// <summary>
	/// Description of MainForm.
	/// </summary>
	public partial class MainForm : Form
	{
		public MainForm()
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			
			//
			// TODO: Add constructor code after the InitializeComponent() call.
			//
		}

		private static string GeneralString(int n, string par)
		{
			System.Text.StringBuilder a = new System.Text.StringBuilder(n * par.Length);
			for (int i=0;i<n;i++)
			{
				a.Append(par);
			}
			return a.ToString();
		}
		
		private void Msg(string sMsg)
		{
			if (sMsg.EndsWith("\r\n"))
				edtResult.AppendText(sMsg);
			else
				edtResult.AppendText(sMsg + "\r\n");
			edtResult.ScrollToCaret();
		}
		
		void BtnTestClick(object sender, EventArgs e)
		{
			if (string.IsNullOrEmpty(etdUri.Text.Trim())) {
				return;
			}
			TestGetApi(etdUri.Text);
		}
		void Button1Click(object sender, EventArgs e)
		{
			string strTemp;
			OpenFileDialog ofd = new OpenFileDialog();
	        ofd.Title = "选择文件(Open)";
	        ofd.FileName = "";
	        ofd.RestoreDirectory = true;
	        ofd.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
	        ofd.ValidateNames = true;
	        ofd.CheckFileExists = true;
	        ofd.CheckPathExists = true;
        	if (ofd.ShowDialog() == DialogResult.OK)
            {
                StreamReader sr = new StreamReader(ofd.FileName, System.Text.Encoding.Default);
                strTemp = sr.ReadToEnd();
            }
        	else
        	{
        		return;
        	}
        	string[] UriList = strTemp.Split(new Char[] { '\r', '\n' });
        	foreach (string str in UriList) {
        		TestGetApi(str);
        	}        	
        	
		}
		
		private void TestGetApi(string uri,string user="",string pwd="")
		{
			string myUri = uri;
			if (string.IsNullOrEmpty(myUri)) {
			    	return;
			}
			Msg(GeneralString(120,"*"));
			if (! myUri.StartsWith("http://")) {
				myUri = "http://" + myUri;
			}
			Msg(myUri);
			HttpWebRequest myRequest = HttpUtils.buildHeader(myUri, "GET");
			if (!string.IsNullOrEmpty(user)) {
				CredentialCache myCache = new CredentialCache();
				myCache.Add(new Uri(uri), "Basic", new NetworkCredential(user, pwd));
				myRequest.Credentials = myCache;
				myRequest.Headers["Authorization"] = 
					"Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(user + ":" + pwd));
			}
			Msg(HttpUtils.Http_state(myRequest));
		}
	}
}
